package com.example.demojimmer.domain.userauth.services;


import com.example.demojimmer.config.SecurityConfig;
import com.example.demojimmer.domain.userauth.model.entity.StUser;
import com.example.demojimmer.domain.userauth.model.entity.StUserFetcher;
import com.example.demojimmer.domain.userauth.model.entity.StUserTable;
import com.example.demojimmer.domain.userauth.model.entity.dto.CreateUserInput;
import com.example.demojimmer.domain.userauth.model.entity.dto.UserView;
import com.example.demojimmer.domain.userauth.repositorise.StUserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户领域服务
 */
@Service
@RequiredArgsConstructor
public class UserService {
    private final PermissionService permissionService;
    private final StUserRepository stUserRepository;

    public SecurityConfig.User registerUser(String username, String password) {
        // 用户注册逻辑
        return new SecurityConfig.User();
    }

    public UserView createUser(CreateUserInput createUserInput) {
        SecurityConfig.User user = null;

        UserView userView = new UserView();
        return userView;
    }

    /**
     * @param unique 唯一性的字段 入参和 登录时UsernamePasswordAuthenticationToken 保持 一致
     * @return
     */
    public SecurityConfig.User findByUsername(String unique) {
       /* QueryWrapper queryWrapper = QueryWrapper.create();
        StUser stUser = this.getOne(queryWrapper.and(StUserTableDef.ST_USER.EMAIL.eq(unique)));

        if (null == stUser) {
            return null;
        }

        User build = User.build(stUser);
        ////查权限
        List<String> permissions = permissionService.queryPermissionsByUserid(stUser.getUserId());
        build.setPermissions(permissions);
        return build;*/
        StUserTable stUserTable = StUserTable.$;
        List<StUser> execute = stUserRepository.sql().createQuery(stUserTable)
                .where(stUserTable.email().eq(unique))
                .select(
                        //构造返回
                        stUserTable.fetch(
                                StUserFetcher.$.allScalarFields()
                        )
                ).execute();


        System.out.println(execute);
        StUser stUser = stUserRepository.findByEmail(unique);
        System.out.println(stUser);

        SecurityConfig.User build = SecurityConfig.User.build(stUser);
        //查权限permissions todo
        if (null == build) {
            return build;
        }
        
        List<String> strings = permissionService.queryPermissionsByUserid(stUser.userId());
        build.setPermissions(strings);
        return build;
    }

}
